from wormbane.generate_level import generate_level
import curses, random
from sys import maxint

HEIGHT, WIDTH = 22, 79


class Engine(object):

    def __init__(self):
        self.seed = random.randint(0, maxint)
        self.level = None

    def update_level(self):
        if self.level is None:
            self.level = generate_level(random.Random(self.seed))


def update_view(stdscr, engine):

    # Update the level view.
    for x, column in enumerate(engine.level.tiles):
        for y, tile in enumerate(reversed(column)):
            if getattr(tile.feature, 'secret', False):
                char = 'S'
            else:
                char = tile.char
            stdscr.addch(y, x, char)

    # Update the status lines.
    status = ['[+-] Seed = %d' % engine.seed]
    status.append('[Q]uit')
    stdscr.addstr(HEIGHT, 0, ('  '.join(status)).ljust(WIDTH)[:WIDTH],
                  curses.A_STANDOUT)


def read_command(stdscr):
    key = stdscr.getch()
    stdscr.nodelay(True)
    while True:
        if stdscr.getch() == -1:
            break
    stdscr.nodelay(False)
    return key


def handle_command(key, engine):

    # Change the random seed.
    if key == ord('+'):
        engine.seed += 1
        engine.level = None
    if key == ord('-'):
        engine.seed -= 1
        engine.level = None


def main(stdscr):
    engine = Engine()
    while True:
        engine.update_level()
        update_view(stdscr, engine)
        key = read_command(stdscr)
        if key in (ord('q'), ord('Q')):
            break
        handle_command(key, engine)


if __name__ == '__main__':
    curses.wrapper(main)
